CONTENTS | INDEX | PREV | NEXT
ungetc
NAME
ungetc - push a character back onto a file pointer's input stream
SYNOPSIS
#include <stdio.h>
int r = ungetc(c, fp);
int c;
FILE *fp;
FUNCTION
ungetc() pushes the specified character back onto the input stream,
as if it had not been read. Only ONE character may be pushed back
onto an input stream at a time. If all went well, the return value
r is equal to c. Else EOF is returned if too many characters were
pushed back.
Some implementations of C allow multiple characters to be pushed
back. The majority, including DICE, allows only one.
ungetc() is useful when, in scanning an input stream, you overshoot
the 'last' character you wanted a particular routine to retrieve.
This routine can push the character back onto the input stream
with ungetc() so another routine's getc() (getchar(), fread(), fgetc(),
etc...) will get that character back.
EXAMPLE
#include <stdio.h>
#include <ctype.h>
main()
{
char buf[256];
void scan_number();
void scan_alpha();
puts("Enter nnnaaannn where n=digit a=alpha. Example: 1234abcd99");
printf("? ");
fflush(stdout);
scan_number();
puts("--");
scan_alpha();
puts("--");
scan_number();
return(0);
}
static void
scan_number()
{
short c;
for (c = getchar(); c >= '0' && c <= '9'; c = getchar()) {
printf("digit: %cn", c);
}
if (c != EOF)
ungetc(c, stdin);
}
static void
scan_alpha()
{
short c;
for (c = getchar(); tolower(c) >= 'a' && tolower(c) <= 'z'; c = getchar()) {
printf("alpha: %cn", c);
}
if (c != EOF)
ungetc(c, stdin);
}
1> testprg
Enter nnnaaannn where n=digit a=alpha. Example: 1234abcd99
? 98charlie55
digit: 9
digit: 8
--
alpha: c
alpha: h
alpha: a
alpha: r
alpha: l
alpha: i
alpha: e
--
digit: 5
digit: 5
1>
INPUTS
int c; character to push back onto input stream
FILE *fp; file pointer stream to push character on to.
RESULTS
int r; pushed character (c) if no error, EOF if error
SEE ALSO
getc, getchar, fread, fgetc